We've come a long, long...
If yellow triangle warnings appear in the editor next to any code we provide in any exercise, it is fine to ignore them.
The very basic building block of JavaScript are primitive data types. We know of three primitives:
- strings (e.g.
"dogs go woof!"
) - numbers (e.g.
4
, 10
) - booleans (e.g.
false
, 5 > 4
)
We learned about the use of comparators (eg. >
, <=
, !==
, etc.). One really important thing to note is that any time comparisons are made, a Boolean value is returned.
There is a long and ugly expression in the editor. Overall, it evaluates to a Boolean (i.e., either the entire statement is true
, or it is false
).
What does this expression in the editor evaluate to?
Declare a variable named answer
. Assign to it the Boolean value that the expression evaluates to. Delete the default code in the editor and run your code.
var answer = (((3 * 90) === 270) || !(false && (!false)) || "bex".toUpperCase() === "BEX");
Through the hard times...
We know two ways of storing data types. We can use variables or arrays. We use variables to store data (like strings or numbers) that we’d later want to access.
An array is exactly the same as a variable in that it stores data. The difference is that an array can store many more values while a variable can only store one.
To access arrays, we use bracket notation and remember that arrays use 0-based indexing (i.e., the first value in an array is at position 0).
Look at the array multiplesOfEight
, and find the one that doesn't fit.
Replace X
in line 6 such that the variable answer
is assigned the Boolean value of true
.
var multiplesOfEight = [8,16,24,32,40,58];
var answer = multiplesOfEight[5] % 8 !== 0;
We're going to play a game of FizzBuzz. The rules are simple. We want to count from 1 to 20. But if the number is divisible by 3, we're going to print "Fizz"
. And if the number is divisible by 5 we're going to print"Buzz"
.
What will we print if the number is divisible by 3 AND 5? That's right!"FizzBuzz"
!
There are many ways to do this, but we'd like you to use a nested conditional in this exercise.
- Print out the numbers from 1 - 20.
- The rules:
- For numbers divisible by 3, print out "Fizz".
- For numbers divisible by 5, print out "Buzz".
- For numbers divisible by both 3 and 5, print out "FizzBuzz" in the console.
- Otherwise, just print out the number.
for(var i = 1; i < 21; i++){
if((i % 3 == 0) && (i % 5 == 0)){
console.log("FizzBuzz");
}
else if(i % 5 == 0){
console.log("Buzz");
}
else if(i % 3 == 0){
console.log("Fizz");
}
else
console.log(i);
}
I have to celebrate you baby
This exercise has lots of movies and reviews to type in. You might wonder, "Is this teaching coding or typing?!"
But there's a reason why there are so many cases to deal with. We want to show that if we used if
-else
statements, it would be inefficient. What alternative to if / else
can we use?
Imagine you have a movie collection, and you want to write code that returns your review for each one. Here are the movies and your reviews:
- "Toy Story 2" - "Great story. Mean prospector."
- "Finding Nemo" - "Cool animation, and funny turtles."
- "The Lion King" - "Great songs."
Write a function named getReview
that takes in a movie name andreturn
s its review based on the information above. If given a movie name not found just return "I don't know!"
. Use a structure learned in an earlier lesson (NOT if
/else
statements) to write this function.
var getReview = function (movie) {
switch(movie) {
case "Toy Story 2":
return ("Great story. Mean prospector.");
case "Finding Nemo":
return "Cool animation, and funny turtles.";
case "The Lion King":
return "Great songs.";
default:
console.log( "I don't know!");
}
};
getReview ("Finding Nemo");
We have discussed four data types: numbers, strings, booleans and arrays.
In this lesson, we focus on a fifth data type: objects. This data type is a little bit more complex. Objects allow us to represent in code real world things and entities (such as a person or bank account). We do this by storing all relevant information in one place—an object.
How do we create an object? Like declaring a variable, or defining a function, we use var
, followed by the name of the object and an equals sign. Each object then:
- starts with
{
- has information inside
- ends with
};
Let's review what we previously covered. Each piece of information we include in an object is known as aproperty. Think of a property like acategory label that belongs to some object. When creating an object, each property has a name, followed by :
and then the value of that property. For example, if we want Bob's object to show he is 34, we'd type in age: 34
.
age
is the property, and 34
is the value of this property. When we have more than one property, they are separated by commas. The last property does not end with a comma.
See the console for the object I have created about myself. Can you create an object called me
that describes your age and which country you live in?
var Spencer = {
age: 22,
country: "United States"
};
var me = {
name: "Jesse",
age: 32,
country: "USA"
}
Now that we know how to make objects with properties, let's look at how we actually use them!
Notice our example objects bob
andsusan
. In this case both bob
andsusan
each have two properties,name
and age
.
After creating our objects we have added code to access these properties. Notice that we save bob
'sname
, "Bob Smith"
, into the global variable name1
. We do this in line 10.
Finish the exercise by filling in the code in lines 13 and 14 to access thename
and age
for susan
and save those into the given global variables.
var bob = {
name: "Bob Smith",
age: 30
};
var susan = {
name: "Susan Jordan",
age: 25
};
var name1 = bob.name;
var age1 = bob.age;
var name2 = susan.name;
var age2 = susan.age;
Accessing Properties, Part 2
In the last exercise, we accessed properties using what is known as dot notation. Good name, right? So to access a property, we useObjectName.PropertyName
(e.g.,bob.name
)
In addition to dot notation, we can also access properties using bracket notation. In this case we useObjectName["PropertyName"]
to access the desired property. Note, we need " "
around the property's name.
Take a look at our next example object called dog
. Notice on line 8 how we save the dog's species into a variable by accessing the species
property ofdog
using bracket notation.
Use bracket notation to save the dog'sweight
and age
into variables as well.
var dog = {
species: "greyhound",
weight: 60,
age: 4
};
var species = dog["species"];
var weight = dog["weight"];
var age = dog["age"]
The method we've used to create objects uses object literal notation—that is, creating a new object with { }
and defining properties within the brackets.
Another way of creating objects without using the curly brackets { }
is to use the keyword new
. This is known as creating an object using aconstructor.
The new
keyword creates an empty object when followed by Object()
. The general syntax is:
var objectName = new Object();
We then have to fill this object with properties and labels. How do we do that? Check out the creation of the object bob
to see what we do. We create the name
property for the object bob
by using bob.name
and assigning that to a value. Contrast this to how we define properties in lines 6-7 for the susan1
object. Inspect the susan1
object carefully and note the use of object literal notation.
Use constructor notation to createsusan2
, which should have the same properties and values as susan1
var bob = new Object();
bob.name = "Bob Smith";
bob.age = 30;
var susan1 = {
name: "Susan Jordan",
age: 24
};
var susan2 = new Object()
susan2.name = "Susan Jordan";
susan2.age = 24;
We've learned how to make objects in two different ways. Both are valid, and you can use which one you prefer.
Let's practice how to use both one more time.
Use literal notation to finish thesnoopy
object. Remember literal notation is the one where we fill in {}
with separate properties and values with colons. Each property is separated by a comma.
snoopy
should have two properties, aspecies
of "beagle"
and age
of 10
.
Then make buddy
, a 5 year-old golden retriever, using constructor notation. This notation involves using the key word new
to create an empty object. Then we fill it in using dot notation
var snoopy = {
species: "beagle",
age: 10
}
var buddy = new Object();
buddy.species = "golden retriever";
buddy.age = 5;
More Practice Making Objects
Nice job! Let's do one more example to get the hang of making objects with desired properties.
Create an object named 'bicycle' that has 3 properties:
- a
speed
of 0 - a
gear
of 1 - a
frame_material
of "carbon fiber”
var bicycle = {
speed: 0,
gear: 1,
frame_material: "carbon fiber"
}
In this lesson we are going to focus onmethods. Methods are an important part of object oriented programming (OOP). OOP is an important part of programming which we'll dive into later.
Methods are similar to functions. To prepare for methods, let's do a quick refresher on functions.
Functions are defined using thefunction
keyword followed by:
- A pair of parentheses
( )
with optional parameters inside. - A pair of curly braces with the function's code inside
{ }
. - A semicolon
.
And when we call the function, we can put inputs (arguments) for the parameters.
For example, the square
function online 2 takes x
as its parameter and returns that parameter squared
Define the function multiply
. It should take two parameters, x
andy
, and return the product.
Then call your function, passing in any two arguments
var square = function (x) {
return x * x;
};
var multiply = function(x, y){
return (x * y);
}
multiply(3, 4);
multiply(10, 10);
In the last section, we discussed properties. We can think of properties as variables associated with an object. Similarly, a method is just like afunction associated with an object.
Let's look at bob
, our same person object from the last lesson. Instead of just having the properties name
andage
(line 3 & 4), bob
also has amethod called setAge
(line 6). As you can probably guess, this method setsbob
's age to whatever argument you give it.
Notice how we define setAge
kind of like we define a property. The big difference is that we put in a function after the equals sign instead of a string or number.
We call a method like a function, but we use ObjectName.methodName()
. Look at line 10 where we use the method to change bob
's age to 40
. We did this by callingbob.setAge(40);
.
var bob = new Object();
bob.name = "Bob Smith";
bob.age = 30;
bob.setAge = function (newAge){
bob.age = newAge;
};
bob.setAge(20);
Why Are Methods Important?
Methods serve several important purposes when it comes to objects.
- They can be used to change object property values. The method
setAge
on line 4 allows us to update bob.age
. - They can be used to make calculations based on object properties. Functions can only use parameters as an input, but methods can make calculations with object properties. For example, we can calculate the year
bob
was born based on his age
with ourgetYearOfBirth
method (line 8).
var bob = new Object();
bob.age = 17;
bob.setAge = function (newAge){
bob.age = newAge;
};
bob.getYearOfBirth = function () {
return 2014 - bob.age;
};
console.log(bob.getYearOfBirth());
Our setAge
method works great forbob
because it updates bob.age
, but what if we want to use it for other people?
It turns out we can make a method work for many objects using a new keyword, this
. The keyword this
acts as a placeholder, and will refer to whichever object called that method when the method is actually used.
Let's look at the method setAge
(line 2) to see how this works. By using the keyword this
, setAge
will change the age
property of any object that calls it. Previously, we had a specific object bob
instead of the keywordthis
. But that limited the use of the method to just bob
.
Then when we say bob.setAge = setAge;
(line 9), it means whenever we type bob.setAge( )
, this.age
in the setAge
method will refer tobob.age
.
To show this way of making setAge
works just like the one in exercise 2, use bob
's setAge
method to change his age to 50
.
var setAge = function (newAge) {
this.age = newAge;
};
var bob = new Object();
bob.age = 30;
bob.setAge = setAge;
bob.setAge(50);
"This" Works for Everyone
Great! Now we can take advantage of the fact that the method setAge
is not limited to a single object bob
—we can reuse the same method for different objects! This allows us to avoid typing out a custom method each time. All because we used the placeholderthis
.
In the editor, we have the same code as last time, where we define setAge
using this
. We then set bob.setAge = setAge;
. But this time we will reuse the setAge
method for susan
as well.
Make susan
on lines 11-13, who should initially have an age of 25
and a susan.setAge
method also equal tosetAge
.
Then use susan.setAge(35);
to setsusan
's age to 35
.
var setAge = function (newAge) {
this.age = newAge;
};
var bob = new Object();
bob.age = 30;
bob.setAge = setAge;
var susan = new Object();
susan.age = 25;
susan.setAge = setAge;
susan.setAge(35);
Let's look at a new example and get practice writing methods.
Here we have defined an objectrectangle
starting on line 1. It has a two properties, height
and width
, which represents the height and width of the shape.
We have written a setHeight
method which will update rectangle
's height
to the given parameter. This is very similar to setAge
from our person example.
Note we have used the keyword this
.this
is still a placeholder, but in this scenario, this
can only ever refer torectangle
because we definedsetHeight
to be explicitly part ofrectangle
by defining it asrectangle.setHeight
Finish the method setWidth
. It should take a parameter newWidth
. It will change the property width
to the given parameter.
Then use the two methods setHeight
and setWidth
to change rectangle
's height to 6
and width to 8
var rectangle = new Object();
rectangle.height = 3;
rectangle.width = 4;
rectangle.setHeight = function (newHeight) {
this.height = newHeight;
};
rectangle.setWidth = function (newWidth) {
this.width = newWidth;
};
rectangle.setWidth(8);
rectangle.setHeight(6)
Let's look at another method that calculates useful information about an object.
Here we have an object square
with asideLength
property to represent the length of the square's side. This time, we have added a new method,calcPerimeter
, which computes the perimeter of the square. Notice we make use of the keyword return
(in the same way we use it in functions!).
Add another method called calcArea
, which returns the area of square
in terms of sideLength
. Use thecalcPerimeter
function as a guide
var square = new Object();
square.sideLength = 6;
square.calcPerimeter = function() {
return this.sideLength * 4;
};
square.calcArea = function() {
return this.sideLength * this.sideLength;
}
var p = square.calcPerimeter();
var a = square.calcArea();
We mentioned the term constructorback in section one, when we talked about making an object using the keyword new
. A constructor is a way to create an object.
When we write bob = new Object( );
we are using a built-in constructor called Object
. This constructor is already defined by the JavaScript language and just makes an object with no properties or methods.
This means we have to add our properties one at a time, just like we've been doing. To review, we've created bob
using the constructor and defined the name
property for you.
var bob = new Object();
bob.name = "Bob Smith";
bob.age = 20;
But this approach of adding in properties one at a time for every object is tedious! Instead of always using the boring Object
constructor, we can make our own constructors.
This way we can set the properties for an object right when it is created. So instead of using the Object
constructor which is empty and has no properties, we can make our own constructors which have properties.
To see how this works, look at ourPerson
constructor in lines 1–4. This constructor is used to make Person
objects. Notice it uses the keywordthis
to define the name
and age
properties and set them equal to the parameters given.
Now we can use this constructor to make our good friends bob
andsusan
in only one line each! Look atlines 7–8: once we have the constructor, it's way easier to make people because we can include theirname
and age
as arguments to their respective constructors.
Practice using the constructor to make a new Person
called george
, whose full name is "George Washington"
and age is 275
function Person(name,age) {
this.name = name;
this.age = age;
}
var bob = new Person("Bob Smith", 30);
var susan = new Person("Susan Jordan", 25);
var george = new Person("George Washington", 275);
Let's look at another example and practice coding constructors. Here we have made a Cat
constructor for you, with age
and color
properties.
Why is this Cat
constructor so cool? It means if we have many cats and wanted to create an object for each cat, we could just use this constructor with the properties already defined.
This is much better than using theObject
constructor which just gives us an empty object and needs us to define every property and value for each cat object we would create.
Finish the Dog
constructor we have started on line 7. You can include whatever parameters and properties you want (age, name, breed, whatever you can think of!) Use the Cat
constructor as an example. function Cat(age, color) {
this.age = age;
this.color = color;
}
function Dog(age, name, breed){
this.age = 12;
this.color = "brown";
this.breed = "mutt";
}
In a constructor, we don't have to define all the properties using parameters. Look at our new Person
example on line 1, and see how we set the species
to be "Homo Sapiens"
(line 4). This means that when we create any Person
, their species
will be "Homo Sapiens"
. In this way, the values associated with name
and age
are not yet assigned, but species
will always have the same value.
In this case, both sally
and holden
will have the same species of "Homo Sapiens"
, which makes sense because that is the same across all people.
Create a new object called sally
using the Person constructor. Her name is "Sally Bowles" and she is 39. Create another object called holden
. His name is "Holden Caulfield" and he is 16.
Edit the sentence printed out such that it includes the age of sally
andholden
respectively
function Person(name,age) {
this.name = name;
this.age = age;
this.species = "Homo Sapiens";
}
var sally = new Person("Sally Bowles", 39);
var holden = new Person("Holden Caulfield", 16);
console.log("sally's species is " + sally.species + " and she is " + sally.age + " " );
console.log("holden's species is " + holden.species + " and he is " + holden.age+ " " );
Constructors With Methods
In addition to setting properties, constructors can also define methods. This way, as soon as the object is created it will have its own methods as well.
Here we have a Rectangle
constructor, which sets the height
and width
properties equal to the arguments, just like our Person
did with name
and age
.
Notice we have added a calcArea
method. This calculates the area of the rectangle in terms of its height and width.
Line 11 creates a new object rex
which makes use of the constructor. You can see how rex calls thecalcArea
method in line 12 and saves the result in a variable, area
.
Define a new method on line 8,calcPerimeter
, which calculates and returns the perimeter for a Rectangle in terms of height
and width
. function Rectangle(height, width) {
this.height = height;
this.width = width;
this.calcArea = function() {
return this.height * this.width;
};
this.calcPerimeter = function(){
return 2*(this.height + this.width);
}
}
var rex = new Rectangle(7,3);
var area = rex.calcArea();
var perimeter = rex.calcPerimeter();
Constructors are a way to make objects with the keyword new
. The most basic constructor is the Object
constructor, which will make an object with no methods or properties.
For more complicated objects we can make our own constructors and put in whatever properties and methods we want.
Check out our example to the right to see objects in action. Our Rabbit
constructor defines an adjective
property and a describeMyself
method.
Recall how these kind of custom constructors are important because they allow us to easily make many similar objects.
Create a new object rabbit1
with the adjective "fluffy"
, a new objectrabbit2
with the adjective "happy"
, and a new object rabbit3
with the adjective"sleepy"
.
Use the method describeMyself
to print out in the console a sentence about each object you just created!
function Rabbit(adjective) {
this.adjective = adjective;
this.describeMyself = function() {
console.log("I am a " + this.adjective + " rabbit");
};
}
var rabbit1 = new Rabbit("fluffy");
var rabbit2 = new Rabbit("happy");
var rabbit3 = new Rabbit("sleepy");
rabbit1.describeMyself();
rabbit2.describeMyself();
rabbit3.describeMyself();
Remember that an object is just anothertype, like a string or number but more complex. This means that just as we can make arrays of numbers and strings, we can also make arrays of objects.
Here we have our Person
constructor which should look familiar. We can use this constructor to make an array ofPerson
objects, similar to how we might make an array of numbers but filling in people instead.
Add one more Person
to the family
array, "timmy"
, who is 6
years old.
function Person (name, age) {
this.name = name;
this.age = age;
}
var family = new Array();
family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
family[3] = new Person("timmy", 6);
Arrays filled with objects will work just like arrays filled with numbers and strings.
In the same way we may loop through an array of numbers to print them out or calculate a sum, we can loop through an array of objects and access properties or methods.
- Write a person constructor called
Person
that has two properties (name
and age
). - Create an empty array called
family
. There will be four objects in the array. Using your Person
constructor, create the four objects and put them in the array. The order of the objects are:
"alice"
who is 40
"bob"
who is 42
"michelle"
who is 8
"timmy"
who is 6
Create a for
-loop that loops through thefamily
array and prints out the name
property for each family member in order of creation.
function Person(name, age){
this.name = name;
this.age = age;
}
var family = new Array();
family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
family[3] = new Person("timmy", 6);
for (var x = 0; x < family.length; x++ ){
console.log(family[x].name);
}
Passing Objects into Functions
In addition to making arrays of Objects, we can use objects as parameters for functions as well. That way, these functions can take advantage of the methods and properties that a certain object type provides.
To see an example, take a look at the console. In addition to our Person
constructor we have introduced a new function, ageDifference
(line 9). This function takes two Person
objects as parameters, and returns the difference in age between the two people.
Notice we would be in trouble here if we tried to call ageDifference
and passed in strings instead of people, because strings don't have an age
property. But because we know from our constructor that allPerson
objects will have an age
property, we can pass any Person
intoageDifference
. We must be careful not to pass anything but Person
objects intoageDifference
.
We have created two example people,alice
and billy
. Complete line 17 by calling ageDifference
and saving the result in our global diff
variable.
function Person (name, age) {
this.name = name;
this.age = age;
}
var ageDifference = function(person1, person2) {
return person1.age - person2.age;
}
var alice = new Person("Alice", 30);
var billy = new Person("Billy", 25);
var diff = ageDifference(alice, billy);
This time try making your own function that takes objects as parameters!
Here we have given you the Person
constructor again, along with theageDifference
function as an example.
Now create a new function, olderAge
. It should take two Person objects as parameters, and return the age
of whatever Person is older. For example, with 30 year-old alice and 25 year-old bob, olderAge(alice, bob);
should return 30
, because that is alice
's age
and she is older than bob
. If the two people have the same age
then you can return that age.
Define a function called olderAge
. We want the function to return the age of the person who is older
function Person (name, age) {
this.name = name;
this.age = age;
}
var ageDifference = function(person1, person2) {
return person1.age - person2.age;
};
var olderAge = function(person1, person2) {
if (person1.age > person2.age) {
return person1.age;
}
else
{
return person2.age;
}
}
var alice = new Person("Alice", 30);
var billy = new Person("Billy", 25);
console.log("The older person is " + olderAge(alice, billy));
Objects provide us with a way to represent real-world or virtual things. We can do this by storing information inside the object's properties. There are two basic ways to make objects:
Literal Notation, where we use
Constructor Notation, where we use the keyword new
.
We've given an example in literal notation to refresh your memory.
Make a new object, spencer2
, with the same properties but using constructor notation and the Object
constructor.
var spencer = {
age: 22,
country: "United States"
};
var spencer2 = new Object()
spencer2.age = 22;
spencer2.country = "United States";
Properties are like variables that belong to an object, and are used to hold pieces of information. Properties can be accessed in two ways:
Dot notation, withObjectName.PropertyName
Bracket notation, withObjectName["PropertyName"]
(don't forget the quotes!)
In the editor, we have brought back oursnoopy
object, with a species
and age
property
Set the global variable species
to be snoopy's species and the variable age
to be snoopy's age. For one use dot notation and the other use bracket notation!
var snoopy = new Object();
snoopy.species = "beagle";
snoopy.age = 10;
var species = snoopy.species;
var age = snoopy['age'];
In addition to the basic Object
constructor, we can define our own custom constructors. These are helpful for two reasons:
- We can assign our objects properties through parameters we pass in when the object is created.
- We can give our objects methods automatically.
These both work to save us time and lines of code when we make objects.
Notice that without the constructor, it takes us 3 lines of code to makeharry_potter
, an object that represents Harry Potter book 1.
Then in line 7 we introduce a constructor for a Book
object, where we pass in thepages
and author
properties as parameters.
Use this constructor to makethe_hobbit
, a book with 320
pages by"J.R.R. Tolkien"
. Notice by using the constructor you can do this in only one line instead of three!
var harry_potter = new Object();
harry_potter.pages = 350;
harry_potter.author = "J.K. Rowling";
function Book (pages, author) {
this.pages = pages;
this.author = author;
}
var the_hobbit = new Book(320, "J.R.R. Tolkien")
Methods are like functions that are associated with a particular object.
They are especially helpful when you want to either:
- Update the object properties
- Calculate something based on an object's properties.
Here, we have included a Circle
object, with a radius
property representing the circle's radius. We have implemented anarea
function which calculates the circle's area. Notice we have usedMath.PI
to get the π value.
Define a method perimeter
that calculates the perimeter of a circle.
function Circle (radius) {
this.radius = radius;
this.area = function () {
return Math.PI * this.radius * this.radius;
};
this.perimeter = function() {
return (2 * (Math.PI * this.radius));
}
};